<?php

namespace app\admin\controller;

//use app\admin\model\User as UserModel;
use think\Controller;
use  app\admin\model\Role as RoleModel;
use think\Db;
use think\Request;


class Role extends Controller
{
    /**
     * 显示管理员列表页.
     *
     * @return \think\Response
     */
    public function index()
    {
        $user=new RoleModel();
        $data=$user->getALL();
//        dump($data);
        return view('role/index',[
        'title'=>'角色列表',
        'data'=>$data
        ]);

    }




    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //        return '添加表单';
        return view('role/create', [
            'title'=>'填个角色!'
        ]);
    }


    /**
     * 保存新建的资源
     *
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $p=$request->post();
//        dump($p);
        $id = Db::name('role')
            ->insertGetId($p);
        $a=[
            'r_id'=>$id,
            'p_id'=>28,
        ];

        $result=Db::table('role_permission')
            ->insert($a);
        if ($result>0) {
            return $this->success('添加成功', url('admin/role/index'));
        } else {
            return $this->error('添加失败,请重试!!');
        }
    }


    /**
     * 加载分配角色
     *
     */
    public function assignPermissions($id)
    {
        $all = db('permission')
            ->select();
//        return array('data' => $all);



        $result = Db::table(['hb_role' => 'r', 'role_permission' => 'rp'])
            ->field('rp.p_id')
            ->where('r.id=rp.r_id')
            ->where('r.id',$id)
            ->select();
        return json(["all"=>$all,"result"=>$result,"rid"=>$id]);
    }

    public function savePermission(Request $request)
    {

        $p=$request->post();

        $rid=$p['id'];
        $pid=json_decode($p['permission']);


        foreach ($pid as $v)
        {
            $data[]=['r_id'=>$rid,'p_id'=>$v];
        }
        Db::table('role_permission')
            ->where('r_id',$rid)
            ->delete();

        Db::table('role_permission')->insertAll($data);

        $roles = Db::table(['hb_permission' => 'p', 'role_permission' => 'rp'])
            ->field(['p.permission'])
            ->where('p.id=rp.p_id')
            ->where('rp.r_id', $rid)
            ->select();


        foreach ($roles as $v){
            $arr[]=$v['permission'];
        }

        $str=implode(' ',$arr);

        return $str;

    }
    /**
     * 删除角色
     * @param rid
     *
     * @return \think\Response
     */
    public function del($id)
    {


        $a= Db::table('hb_role')->where('id',$id)->delete();
        $b= Db::table('user_role')->where('r_id',$id)->delete();
        $c= Db::table('role_permission')->where('r_id',$id)->delete();

//        if ($a && $b ){
            return $id;
//        }
    }


}
